package cn.itsource.pet.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.itsource.basic.dto.SearchMasterMsgDto;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.util.*;
import cn.itsource.basic.util.Point;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.domain.TEmployee;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.pet.domain.OrderPetAcquisition;
import cn.itsource.pet.domain.SearchMasterMsg;
import cn.itsource.pet.domain.SearchMasterMsgAuditLog;
import cn.itsource.pet.mapper.OrderPetAcquisitionMapper;
import cn.itsource.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.itsource.pet.mapper.SearchMasterMsgMapper;
import cn.itsource.pet.query.SearchMasterMsgQuery;
import cn.itsource.pet.service.ISearchMasterMsgService;
import cn.itsource.basic.service.impl.BaseImpl;
import cn.itsource.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private LoginContext loginContext;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Transactional
    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        //1.校验 - 空值校验
        if (StrUtil.isBlank(msg.getTitle()) || StrUtil.isBlank(msg.getName()) || StrUtil.isBlank(msg.getAddress())) {
            throw new BusinessException("标题、姓名、地址不能为空");
        }
        //2.校验 - 百度AI只能审核
        Boolean boo1 = BaiduAIUtils.textCensor(msg.getTitle() + msg.getName());
        Boolean boo2 = BaiduAIUtils.imgCensor(msg.getResources());
        boo1=boo2=true;

        //3.保存数据库 - 下一步人工审核【后台管理系统】
        if (boo1 && boo2) {
            User user = (User) loginContext.getLoginObject(request);
            msg.setUserId(user.getId());
            searchMasterMsgMapper.insert(msg);

        } else {
            throw new BusinessException("图片或文字包含违规内容");
        }

        return new AjaxResult();
    }

    @Override
    public PageResult<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);
        TEmployee employee = (TEmployee) loginContext.getLoginObject(request);
        if (employee.getShopId() != null) {
            query.setShopId(employee.getShopId());
        }
        return super.selectByQueryPage(query);
    }

    @Override
    public PageResult<SearchMasterMsg> pool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);
        return super.selectByQueryPage(query);
    }

    @Override
    public PageResult<SearchMasterMsg> toAudit(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(0);
        TEmployee employee = (TEmployee) loginContext.getLoginObject(request);
        if (employee.getShopId() != null) {
            throw new BusinessException("只有店铺管理员才能查看待审核信息");
        }
        return super.selectByQueryPage(query);
    }

    @Override
    public PageResult<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);
        TEmployee employee = (TEmployee) loginContext.getLoginObject(request);
        if (employee.getShopId() != null) {
            query.setShopId(employee.getShopId());
        }
        return super.selectByQueryPage(query);
    }

    @Override
    public AjaxResult audit(SearchMasterMsgAuditLog log, HttpServletRequest request) {
        SearchMasterMsg msg = searchMasterMsgMapper.selectById(log.getMsgId());
        //审核成功 1分配最近的店铺 2更新状态为1或3分别指代找到店铺和放到寻主池 3告诉店铺
        //审核失败 1

        if (log.getState() == 1) {
            //1分配最近的店铺
            Point point = DistanceUtils.getPoint(msg.getAddress());//寻主发布时的地址
            Shop shop = DistanceUtils.getNearestShop(point, shopMapper.selectAll());
            if (shop == null) {
                //放入寻主池并更新状态
                msg.setState(3);

            } else {//找到店铺的情况下
                //设置店铺并更新状态
                msg.setShopId(shop.getId());
                msg.setState(1);
                System.out.println("新订单");

            }
        } else {
            msg.setState(-1);
            System.out.println("审核失败");
        }

        //添加日志

        TEmployee employee = (TEmployee) loginContext.getLoginObject(request);

        log.setAuditId(employee.getId());
        searchMasterMsgAuditLogMapper.insert(log);

        //更新寻主消息状态
        searchMasterMsgMapper.update(msg);
        return new AjaxResult();
    }

    @Override
    public AjaxResult reject(Long msgId) {
        //拒单: 消息已经分配给店铺了，店铺因为某些原因拒接接单 - 拒单之后寻主消息放入寻主池
        searchMasterMsgMapper.reject(msgId);
        /*SearchMasterMsg msg = searchMasterMsgMapper.findOne(msgId);
        msg.setState(3);
        msg.setShopId(null);
        searchMasterMsgMapper.update(msg);*/
        return new AjaxResult();
    }

    @Override
    public AjaxResult accept(SearchMasterMsgDto searchMasterMsgDto) {
        Long msgId = searchMasterMsgDto.getMsgId();
        //接单：消息已经分配给店铺，店铺同意接单-生成收购订单-然后处理订单
        //判断当前订单是否在处理，如果生成收购订单说明正在处理
        OrderPetAcquisition order = orderPetAcquisitionMapper.findByMsgId(msgId);
        if (order != null) {
            throw new BusinessException("该订单正在处理中");
        }

        //1.生成订单
        SearchMasterMsg msg = searchMasterMsgMapper.selectById(msgId);
        OrderPetAcquisition orderPetAcquisition = dtoToOrder(msg, searchMasterMsgDto);
        orderPetAcquisitionMapper.insert(orderPetAcquisition);

        //2.给处理人发送短信,让他及时处理订单
        System.out.println("订单已发送，请及时处理");
        return new AjaxResult();
    }

    private OrderPetAcquisition dtoToOrder(SearchMasterMsg msg, SearchMasterMsgDto searchMasterMsgDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(searchMasterMsgDto.getNote());
        //最后确认时间
        order.setLastcomfirmtime(
                new Date(System.currentTimeMillis() + 3 * 24 * 60 * 60 * 1000));
        order.setState(0); //订单状态:0待处理，1完成，-1取消
        order.setPrice(msg.getPrice());
        //支付类型和宠物id订单处理完成才有
        //order.setPaytype(0);
        //order.setPetId():
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(searchMasterMsgDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());

        return order;
    }


}
